// 原生闹钟管理器
class AlarmManager {
  constructor() {
    this.alarms = new Map();
  }

  // 设置系统级闹钟
  setSystemAlarm(alarm) {
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass("android.content.Context");
      const AlarmManager = plus.android.importClass("android.app.AlarmManager");
      const Intent = plus.android.importClass("android.content.Intent");
      const PendingIntent = plus.android.importClass(
        "android.app.PendingIntent"
      );
      const Calendar = plus.android.importClass("java.util.Calendar");

      // 获取AlarmManager服务
      const alarmManager = main.getSystemService(Context.ALARM_SERVICE);

      // 创建Intent
      const intent = new Intent(main, main.getClass());
      intent.setAction("ALARM_TRIGGER");
      intent.putExtra("alarmId", alarm.id);
      intent.putExtra("alarmLabel", alarm.label);
      intent.putExtra("alarmTime", alarm.time);
      intent.putExtra("vibrate", alarm.vibrate);

      // 创建PendingIntent
      const pendingIntent = PendingIntent.getActivity(
        main,
        alarm.id,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
      );

      // 计算闹钟时间
      const calendar = Calendar.getInstance();
      const [hours, minutes] = alarm.time.split(":").map(Number);

      if (alarm.type === "once" && alarm.date) {
        // 一次性闹钟
        const alarmDate = new Date(alarm.date);
        calendar.set(Calendar.YEAR, alarmDate.getFullYear());
        calendar.set(Calendar.MONTH, alarmDate.getMonth());
        calendar.set(Calendar.DAY_OF_MONTH, alarmDate.getDate());
      } else {
        // 重复闹钟 - 设置为今天或明天
        const now = new Date();
        const today = new Date(
          now.getFullYear(),
          now.getMonth(),
          now.getDate(),
          hours,
          minutes
        );

        if (today <= now) {
          // 如果时间已过，设置为明天
          calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
      }

      calendar.set(Calendar.HOUR_OF_DAY, hours);
      calendar.set(Calendar.MINUTE, minutes);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.MILLISECOND, 0);

      // 设置精确闹钟
      if (android.os.Build.VERSION.SDK_INT >= 23) {
        alarmManager.setExactAndAllowWhileIdle(
          AlarmManager.RTC_WAKEUP,
          calendar.getTimeInMillis(),
          pendingIntent
        );
      } else {
        alarmManager.setExact(
          AlarmManager.RTC_WAKEUP,
          calendar.getTimeInMillis(),
          pendingIntent
        );
      }

      console.log(`系统闹钟已设置: ${alarm.time} - ${alarm.label}`);
      return true;
    } catch (error) {
      console.error("设置系统闹钟失败:", error);
      return false;
    }
    // #endif

    // #ifndef APP-PLUS
    console.log("非APP环境，无法设置系统闹钟");
    return false;
    // #endif
  }

  // 取消系统级闹钟
  cancelSystemAlarm(alarmId) {
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass("android.content.Context");
      const AlarmManager = plus.android.importClass("android.app.AlarmManager");
      const Intent = plus.android.importClass("android.content.Intent");
      const PendingIntent = plus.android.importClass(
        "android.app.PendingIntent"
      );

      const alarmManager = main.getSystemService(Context.ALARM_SERVICE);

      const intent = new Intent(main, main.getClass());
      intent.setAction("ALARM_TRIGGER");

      const pendingIntent = PendingIntent.getActivity(
        main,
        alarmId,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
      );

      alarmManager.cancel(pendingIntent);
      console.log(`系统闹钟已取消: ${alarmId}`);
      return true;
    } catch (error) {
      console.error("取消系统闹钟失败:", error);
      return false;
    }
    // #endif

    return false;
  }

  // 处理闹钟触发
  handleAlarmTrigger(intent) {
    // #ifdef APP-PLUS
    try {
      const alarmId = intent.getIntExtra("alarmId", -1);
      const alarmLabel = intent.getStringExtra("alarmLabel");
      const alarmTime = intent.getStringExtra("alarmTime");
      const vibrate = intent.getBooleanExtra("vibrate", false);

      console.log("闹钟触发:", { alarmId, alarmLabel, alarmTime, vibrate });

      // 震动
      if (vibrate) {
        this.performVibration();
      }

      // 显示通知
      this.showAlarmNotification(alarmLabel, alarmTime);

      // 播放提示音
      plus.device.beep(5);

      // 唤醒屏幕
      plus.device.wakelock();

      return true;
    } catch (error) {
      console.error("处理闹钟触发失败:", error);
      return false;
    }
    // #endif

    return false;
  }

  // 执行震动
  performVibration() {
    let count = 0;
    const vibrate = () => {
      if (count < 10) {
        uni.vibrate({
          success: () => console.log(`震动 ${count + 1}`),
          fail: (err) => console.error("震动失败:", err),
        });
        count++;
        setTimeout(vibrate, 1000);
      }
    };
    vibrate();
  }

  // 显示闹钟通知
  showAlarmNotification(label, time) {
    // #ifdef APP-PLUS
    try {
      plus.push.createMessage(`${time} - ${label}`, "", {
        title: "⏰ 闹钟提醒",
        when: new Date(),
        cover: false,
      });
    } catch (error) {
      console.error("创建通知失败:", error);
    }
    // #endif
  }
}

export default new AlarmManager();
